﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

namespace GameCore {
    /// <summary>
    /// UI物件创建器，避免清空，重新生成子物体
    /// </summary>
    public class UIItemsView : MonoBehaviour
    {
        /// <summary>
        /// 刷新回调
        /// </summary>
        public Action<GameObject, int> UpdateItem;
        /// <summary>
        /// 预制体
        /// </summary>
        public GameObject prefab;
        /// <summary>
        /// 缓存池
        /// </summary>
        SimplePool pool;
        public void Init(int count)
        {
            if (prefab == null) {
                Logger.LogError("请给一个预制体，或者在组件下放一个默认的游戏物体！");
                return;
            }
            if(prefab.transform.IsChildOf(this.transform))
                this.prefab.gameObject.SetActive(false);
            if (pool == null)
                pool = new SimplePool(prefab);
            pool.CollectAll();
            GameObject gameObj = null;
            for (int i = 0; i < count; i++) {
                gameObj = pool.GetOne();
                gameObj.name = i.ToString();
                RectTransform rectTrans = gameObj.transform as RectTransform;
                rectTrans.SetParent(this.transform);
                rectTrans.localPosition = Vector3.zero;
                rectTrans.localScale = Vector3.one;
                rectTrans.SetAsLastSibling();//设置为同级最后
                if (UpdateItem != null)
                    UpdateItem(gameObj,i);
            }
        }

        private void OnDestroy()
        {
            if(pool!=null)
                pool.Dispose();
        }
    }
}

